package com.store.app.activity;


import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;
import android.webkit.WebSettings.LayoutAlgorithm;
import android.webkit.WebView;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.store.app.BaseActivity;
import com.store.app.ExitApplication;
import com.store.app.MainActivity;
import com.store.app.R;
import com.store.app.bean.BitmapBean;
import com.store.app.http.Stores;
import com.store.app.net.NetRequest;
import com.store.app.net.ifc.IOnHttpListener;
import com.store.app.stores.MultipartEntity;
import com.store.app.utils.GoToLogin;
import com.store.app.utils.SettingData;
import com.store.app.utils.Utils;
import com.store.app.utils.UtilsBitmap;
import com.store.app.widget.BookedOnlinePopupWindow;
import com.store.app.widget.ProgressWebView;
import com.store.app.widget.ShareDialog;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.yalantis.ucrop.CropUtils;
import com.yalantis.ucrop.UCrop;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.InputStream;
import java.util.Date;

/**
 * 推广页面
 */
public class WebViewTGActivity extends BaseActivity implements SwipeRefreshLayout.OnRefreshListener, OnClickListener ,IOnHttpListener{
    private TextView tv, tv_right;
    private ProgressWebView webView;
    private String title;
    private String urls = "", id = "";
    private LinearLayout lin_right;
    private ProgressBar progressBar;
    private SwipeRefreshLayout mSwipeLayout;
    private LinearLayout lin_all;
    private RelativeLayout loadfail;
    private LinearLayout lin_loadNull;//加载为空
    private LinearLayout lin_loadfail;  //无网络页面
    private TextView tvReload;
    private BookedOnlinePopupWindow bp_online;
    private PopupWindow mPop;
    private final int POST_SUCC = 8;
    private final int POST_FAIL = 9;
    private String errorMsg;
    private GoToLogin goToLogin;
    //图片地址
    private String img_add = "";
    private UMImage image;//分享时候的图标
    private String shareTitle;//分享标题
    private String shareText;//分享内容
    private ShareDialog mShareDialog;//分享时候的弹窗
    private UMShareAPI mShareAPI;
    private String shareUrl;//分享链接
    private NetRequest netRequest;

    public WebViewTGActivity() {
        super();
    }

    private String methodReturn;//回调方法名
    private String from = "";
    private static String localTempImageFileName = "";

    private static final int FLAG_CHOOSE_IMG = 5;
    private static final int FLAG_CHOOSE_PHONE = 6;
    private static final int FLAG_MODIFY_FINISH = 7;
    private String picData;
    private Handler myHandler = new Handler() {
        @SuppressLint("NewApi")
        @Override
        public void handleMessage(Message msg) {// handler接收到消息后就会执行此方法
            super.handleMessage(msg);
            switch (msg.what) {

                case 2:

                    Log.v("zyl", "methodReturn:" + methodReturn);
                    Log.v("zyl", "picData:" + picData);
                    webView.loadUrl("javascript:" + methodReturn + "(" + picData + ")");
                    break;
            }
        }
    };

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ExitApplication.getInstance().addActivity(this);
        setContentView(R.layout.activity_webview);
        urls = getIntent().getStringExtra("url");
        title = getIntent().getStringExtra("title");
        goToLogin = new GoToLogin(this);
        netRequest = new NetRequest(this);
        findViews();
        setWebView();
        if (Build.VERSION.SDK_INT >= 19) {//硬件加速器的使用
            webView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
        } else {
            webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
        }

    }


    private void setWebView() {
        webView.clearCache(true);
        webView.loadUrl(urls);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setLoadsImagesAutomatically(true);
        webView.getSettings().setBuiltInZoomControls(true);
        webView.getSettings().setDefaultTextEncodingName("utf-8");
        webView.getSettings().setLayoutAlgorithm(LayoutAlgorithm.NORMAL);
        webView.getSettings().setDomStorageEnabled(true);
        webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);//设置不使用缓存
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            webView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        webView.setWebViewClient(new WebViewClient1()
        );
        webView.setWebChromeClient(new WebChromeClient1());
        webView.addJavascriptInterface(new JSInterface(), "jsObj");


    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.public_ll_right:
                finish();
                break;
            case R.id.tv_right1:

                break;
        }
    }

    @Override
    public void onAfinalFail() {

    }

    @Override
    public void onExecuteSuccess(int requestId, String result, String msg) {

        if (requestId==4){
            //图片上传成功
            try {
                JSONObject data = new JSONObject(result);
                Log.v("zyl", "data:" + data.toString());
                picData = "";
                picData = data.toString();
                myHandler.sendEmptyMessage(2);
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }

    }

    @Override
    public void onExecuteFail(int requestId, String msg) {

    }

    final class JSInterface {

        private Handler handler = new Handler();


        @JavascriptInterface
        public void share(final String string) {
            handler.post(new Runnable() {
                @Override
                public void run() {
                    Log.v("zyl", "share:" + string);
                    try {
                        JSONObject jsonObject = new JSONObject(string);
                        String title = jsonObject.getString("title");
                        String desc = jsonObject.getString("desc");
                        String imgPath = jsonObject.getString("imgPath");
                        String url = jsonObject.getString("url");
                        shareUrl = url;
                        image = new UMImage(WebViewTGActivity.this, imgPath);
                        shareTitle = title;
                        shareText = desc;

                        mShareDialog = new ShareDialog(WebViewTGActivity.this, listener);
                        mShareDialog.show();
                    } catch (Exception e) {

                    }

                }

            });
        }

        //上传图片
        @JavascriptInterface
        public void uploadImg(final String s) {
            handler.post(new Runnable() {
                @Override
                public void run() {
                    methodReturn = s;
                    getPic();
                }
            });
        }

        //打开广告页
        @JavascriptInterface
        public void openAdLayer(final String jsonData) {
            handler.post(new Runnable() {
                @Override
                public void run() {
                    Log.v("zyl", "openAdLayer jsonData:" + jsonData);
                    try {
                        JSONObject jsonObject = new JSONObject(jsonData);
                        String url = jsonObject.getString("url");
                        Intent intent = new Intent(WebViewTGActivity.this, WebViewAdActivity.class);
                        intent.putExtra("url", url);
                        startActivity(intent);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

            });
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);


        if (requestCode == FLAG_CHOOSE_IMG && resultCode == RESULT_OK) {
            if (data != null) {
                Uri uri = data.getData();
                CropUtils.startCropActivity(uri, WebViewTGActivity.this, 5, 5);
            }
        } else if (requestCode == FLAG_CHOOSE_PHONE && resultCode == RESULT_OK) {

            File f = new File(SettingData.FILE_PIC_SCREENSHOT, localTempImageFileName);
            Uri uri = Uri.fromFile(f);
            CropUtils.startCropActivity(uri, WebViewTGActivity.this, 5, 5);

        } else if (requestCode == UCrop.REQUEST_CROP && resultCode == RESULT_OK) {
            //剪切成功
            if (data != null) {
                final Uri resultUri = UCrop.getOutput(data);
                BitmapBean bitmapBean = UtilsBitmap.addFilePath3(resultUri.getPath(), this);

                if (bitmapBean.getIsBm() != null) {
                    netRequest.requestUploadPic(4, bitmapBean.getIsBm());
                }
//                new uploadtask(vistabitmap).start();
            }
        } else if (resultCode == UCrop.RESULT_ERROR) {
            //剪切失败
            Toast.makeText(WebViewTGActivity.this, "图片剪切失败！", Toast.LENGTH_SHORT)
                    .show();
        }
    }

    private class uploadtask extends Thread {
        Bitmap bitmap;

        public uploadtask(Bitmap bitmap) {
            this.bitmap = bitmap;
        }

        public void run() {
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.PNG, 10, stream);
            InputStream in = new ByteArrayInputStream(stream.toByteArray());
            DefaultHttpClient httpclient = new DefaultHttpClient();
            try {
                HttpPost httppost = new HttpPost(Stores.http
                        + "/ops-storage/storage/upload");
                MultipartEntity reqEntity = new MultipartEntity();
                reqEntity.addPart("app_token", MainActivity.app_token);
                reqEntity.addPart("category", "oss_community");
                reqEntity.addPart("subffix", "jpg");
                reqEntity.addPart("up_load_file", "pic.jpg", in);
                httppost.setEntity(reqEntity);
                HttpResponse response = null;
                response = httpclient.execute(httppost);
                response.getStatusLine().toString();
                String strResult = EntityUtils.toString(response.getEntity());
                JSONObject obj = new JSONObject(strResult);
                String rsp_code = obj.getString("rsp_code");
                if (rsp_code.equals("succ")) {
                    JSONObject data = obj.getJSONObject("data");
                    Log.v("zyl", "data:" + data.toString());
                    picData = "";
                    picData = data.toString();
                    myHandler.sendEmptyMessage(2);

                } else {
                }
                in.close();
                stream.close();

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public void getPic() {
        new AlertDialog.Builder(WebViewTGActivity.this)
                .setTitle("请选择图片来源")
                .setItems(new String[]{"相册", "相机"},
                        new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog,
                                                int which) {
                                if (which == 0) {
                                    Intent intent = new Intent(
                                            Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                                    startActivityForResult(intent,
                                            FLAG_CHOOSE_IMG);
                                } else if (which == 1) {
                                    String status = Environment
                                            .getExternalStorageState();
                                    if (status
                                            .equals(Environment.MEDIA_MOUNTED)) {
                                        try {
                                            localTempImageFileName = "";
                                            localTempImageFileName = String
                                                    .valueOf((new Date())
                                                            .getTime())
                                                    + ".png";
                                            File filePath = SettingData.FILE_PIC_SCREENSHOT;
                                            if (!filePath.exists()) {
                                                filePath.mkdirs();
                                            }
                                            Intent intent = new Intent(
                                                    MediaStore.ACTION_IMAGE_CAPTURE);
                                            File f = new File(filePath,
                                                    localTempImageFileName);
                                            // localTempImgDir和localTempImageFileName是自己定义的名字
                                            Uri u = Uri.fromFile(f);
                                            intent.putExtra(
                                                    MediaStore.Images.Media.ORIENTATION,
                                                    0);
                                            intent.putExtra(
                                                    MediaStore.EXTRA_OUTPUT,
                                                    u);
                                            startActivityForResult(
                                                    intent,
                                                    FLAG_CHOOSE_PHONE);
                                        } catch (ActivityNotFoundException e) {
                                            //
                                        }
                                    }
                                }

                            }
                        }).show();
    }

    public void showLoadResult(int state) {
        //无网络情况
        if (state == 1) {
            loadfail.setVisibility(View.VISIBLE);
            lin_loadfail.setVisibility(View.VISIBLE);
            lin_loadNull.setVisibility(View.GONE);
        }//无数据情况
        else if (state == 2) {
            Log.v("zyl", "无数据");
            loadfail.setVisibility(View.VISIBLE);
            lin_loadfail.setVisibility(View.GONE);
            lin_loadNull.setVisibility(View.VISIBLE);
        }//都不显示
        else {
            loadfail.setVisibility(View.GONE);
        }
    }

    public class WebViewClient1 extends android.webkit.WebViewClient {
        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {                 // Handle the error
            Log.v("zyl", "onReceivedError网络加载不出来");
//            webView.loadDataWithBaseURL ( null, "", "text/html", "utf-8", null );

            //停止webView的所有操作
            webView.onPause();
            webView.pauseTimers();
//			lin_loadfail.setVisibility(View.VISIBLE);
            showLoadResult(1);
//			Toast.makeText(WebViewBookedActivity.this,"description:"+description,Toast.LENGTH_SHORT).show();
        }


        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            Log.v("zyl", "变化的URL:" + url);
            if (url.startsWith("http:") || url.startsWith("https:")) {
                return false;
            }

            // Otherwise allow the OS to handle things like tel, mailto, etc.
            try {
                Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                startActivity(intent);
            } catch (Exception e) {

            }
            return true;
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            Log.v("zyl", "onPageStart:" + url);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            if (url.startsWith("http")) {
                urls = url;
            }
        }

    }

    public class WebChromeClient1 extends android.webkit.WebChromeClient {
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            Log.v("zyl", "加载进度：" + newProgress);
            if (newProgress == 100) {
                progressBar.setVisibility(View.GONE);
            } else {
                if (progressBar.getVisibility() == View.GONE)
                    progressBar.setVisibility(View.VISIBLE);
                progressBar.setProgress(newProgress);
            }
            super.onProgressChanged(view, newProgress);
        }


    }

    public void onPause() {//继承自Activity
        super.onPause();
        webView.onPause();

        webView.pauseTimers();
        if (isFinishing()) {
            Log.v("zyl", "isFinishing");
            webView.loadUrl("about:blank");
            setContentView(new FrameLayout(this));
        }
    }

    public void onResume() {//继承自Activity
        super.onResume();
        webView.onResume();
        webView.resumeTimers();
    }

    private void findViews() {
        lin_right = (LinearLayout) findViewById(R.id.public_ll_right);
        lin_right.setOnClickListener(this);
        tv_right = (TextView) findViewById(R.id.public_tv_right);
        tv_right.setBackgroundResource(R.drawable.pic_icon_close_x);
        progressBar = (ProgressBar) findViewById(R.id.progressbar);
        loadfail = (RelativeLayout) findViewById(R.id.loadfail);

        lin_loadfail = (LinearLayout) findViewById(R.id.ll_load_fail);//无网络
        lin_loadNull = (LinearLayout) findViewById(R.id.ll_load_null);//无网络
        tvReload = (TextView) findViewById(R.id.tv_reload);
        tvReload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Utils.isFastClick()) {
                    return;
                }
                showLoadResult(3);
                webView.clearCache(true);
                webView.clearHistory();
                webView.clearFormData();
                webView.loadUrl(urls);
            }
        });
        lin_all = (LinearLayout) findViewById(R.id.lin_all);
        webView = (ProgressWebView) findViewById(R.id.onlcon_web);
        webView.setContext(this);

        tv = (TextView) findViewById(R.id.tvTitle);
        tv.setText(title);
        findViewById(R.id.public_ll_return).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (webView.canGoBack() && !"about:blank".equals(webView.getUrl())) {
                    webView.goBack();// 返回前一个页面
                } else {
                    finish();
                }
            }
        });

        mSwipeLayout = (SwipeRefreshLayout) findViewById(R.id.sw);
        mSwipeLayout.setOnRefreshListener(this);

        mShareAPI = UMShareAPI.get(this);

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && webView.canGoBack() && !"about:blank".equals(webView.getUrl())) {
            webView.goBack();// 返回前一个页面
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onDestroy() {

        super.onDestroy();
    }

    @Override
    public void onRefresh() {
        setWebView();
        mSwipeLayout.setRefreshing(false);
    }


    ShareDialog.OnShareClickListener listener = new ShareDialog.OnShareClickListener() {
        @Override
        public void FriendCircle(View v) {
            new ShareAction(WebViewTGActivity.this).setPlatform(SHARE_MEDIA.WEIXIN_CIRCLE).setCallback(umShareListener)
                    .withTitle(shareTitle)
                    .withMedia(image)
                    .withText(shareText)
                    .withTargetUrl(shareUrl)
                    .share();
            mShareDialog.dismiss();
        }

        @Override
        public void WeChatFriends(View v) {
            new ShareAction(WebViewTGActivity.this).setPlatform(SHARE_MEDIA.WEIXIN).setCallback(umShareListener)
                    .withTitle(shareTitle)
                    .withMedia(image)
                    .withText(shareText)
                    .withTargetUrl(shareUrl)
                    .share();
            mShareDialog.dismiss();
        }

        @Override
        public void QQFriends(View v) {
            new ShareAction(WebViewTGActivity.this).setPlatform(SHARE_MEDIA.QQ).setCallback(umShareListener)
                    .withTitle(shareTitle)
                    .withMedia(image)
                    .withText(shareText)
                    .withTargetUrl(shareUrl)
                    .share();
            mShareDialog.dismiss();

        }

        @Override
        public void QQZone(View v) {
            new ShareAction(WebViewTGActivity.this).setPlatform(SHARE_MEDIA.QZONE).setCallback(umShareListener)
                    .withTitle(shareTitle)
                    .withMedia(image)
                    .withText(shareText)
                    .withTargetUrl(shareUrl)
                    .share();
            mShareDialog.dismiss();
        }

        @Override
        public void Copy(View v) {

        }

        @Override
        public void SMS(View v) {

        }


        @Override
        public void Email(View v) {
        }
    };
    private UMShareListener umShareListener = new UMShareListener() {
        @Override
        public void onResult(SHARE_MEDIA platform) {

            Toast.makeText(WebViewTGActivity.this, " 分享成功啦", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
            Toast.makeText(WebViewTGActivity.this, " 分享失败啦", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onCancel(SHARE_MEDIA platform) {
            if ("QQ".equals(platform.toString())) {
                // Toast.makeText(ShareApplicationActivity.this, " 分享成功啦", Toast.LENGTH_SHORT).show();
            } else {
//                Toast.makeText(WebViewBookedActivity.this, " 分享取消了", Toast.LENGTH_SHORT).show();
            }
        }
    };

//    @Override
//    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//        super.onActivityResult(requestCode, resultCode, data);
//
//    }
}
